<template>
  <div class="reg-page">
    <group class="reg-group">
      <div class="sel-item">
        <div class="label" style="line-height: 22px;">考生类型</div>
        <div class="radio-group" v-for="(item, idx) in examTypes" :key="idx+10">
          <div class="radio-item" @click="examTypeChang(idx)">
            <div class="radio-room">
              <span class="weui-icon-checked" :class="[{'i-checked': item.checked}]"></span>
            </div>
            <div class="radio-txt">{{item.txt}}</div>
          </div>
        </div>
      </div>
    </group>
    <div class="reg-title">成绩位次</div>
    <group class="reg-group">
      <popup-picker v-if="art.examType == 2" class="art-pop" title="请选择科类代码" :data="artArr" v-model="artVal" @on-change="onArtChange" placeholder="选择专业科目"></popup-picker>
      <x-input v-if="art.examType == 2" :max=3 class="def-ipt" title="专业省统考成绩" :disabled="changeCount == 0 ? true: false" v-model="art.artScore"  @on-blur="verifArtScore(art.artScore)" type="tel" label-width="122px" placeholder="请输入专业分数"></x-input>
      <x-input :max=3 v-for="(item, idx) in mainSub" class="def-ipt" :key="idx+20" :disabled="changeCount == 0 ? true: false" :title="item.name" v-model="item.score" @click.native="onMainClick(idx)" @on-blur="verifScore(item.score, 150, idx)" type="tel" label-width="80px" :placeholder="'请输入'+item.name+'成绩'"></x-input>
      <!-- <div class="reg-title">选考科目选择（七选三）</div> -->
      <div class="sel-item" v-for="(item, idx) in sel73" :key="idx+30" >
        <div class="label">{{item.name}}</div>
        <div class="ipt-item">
          <input type="tel" maxlength="3" v-model="item.score"  @click="hasDisable(idx)" :disabled="inputDisable[idx] || changeCount == 0 ? true: false" @blur="verifSubject(item.score, 100, idx)" placeholder="请输入您的成绩">
        </div>
        <div class="check-room" @click="subjectClick(idx)">
          <span class="weui-icon-checked" :class="[{'i-checked': selectSubject[idx]}]"></span>
        </div>
      </div>
      <popup-picker class="points-pop" title="加分项" :disabled="changeCount == 0 ? true: false" :data="plusScoreArr" v-model="plusScoreVal" @on-change="onPlusScoreChange" placeholder="选择加分项"></popup-picker>
    </group>
    <div class="reg-title">高考成绩</div>
    <group class="reg-group">
      <x-input title="2019成绩" :value="score" class="highlight" label-width="120px" disabled readonly></x-input>
      <x-input title="高考位次" type="tel" v-model="rank" class="highlight" label-width="120px"></x-input>
      <x-input title="2018/2017成绩" :value="`${score2018} / ${score2017}`" class="highlight" label-width="120px" disabled readonly></x-input>
    </group>
    <div class="reg-tip" v-if="changeCount > 0 && userData &&　userData.type == 102">您是体验用户，还有{{changeCount}}次修改成绩的机会！
      <div class="goto-buy-wrap">
        <!-- <img class="goto-buy-img" src="@/assets/images/go_buy.png"> -->
        <a href="javascript:;" @click="gotoBuy" class="goto-buy">去购买</a>
      </div>
    </div>
    <div class="reg-tip" v-if="changeCount == 0 && userData &&　userData.type == 102">您是体验用户，已经没有修改成绩的机会！
      <div class="goto-buy-wrap">
        <!-- <img class="goto-buy-img" src="@/assets/images/go_buy.png"> -->
        <a href="javascript:;" @click="gotoBuy" class="goto-buy">去购买</a>
      </div>
    </div>
    <!-- <div class="reg-tip" v-else>注：该页信息在高考查询状态下可无限次修改成绩和位次号；选考科目选择和个人信息一旦确定不能修改。若需修改，请另外注册账号查询。</div> -->
    <div class="btn-next-group">
      <a href="javascript:;" class="btn-next" v-if="changeCount" @click="saveScoureRank()">保存</a>
    </div>
  </div>
</template>

<script>
import Api from '@/api/index.js'
import Utils from '@/common/utils.js'
import { CheckIcon, Group, PopupPicker, Radio, XInput } from 'vux'
export default {
  components: {
    CheckIcon,
    Group,
    PopupPicker,
    Radio,
    XInput
  },
  data () {
    return {
      userData: null,
      mainSub: [
        {
          name: '语文',
          tscore: null,
          score: ''
        },
        {
          name: '数学',
          tscore: null,
          score: ''
        },
        {
          name: '外语',
          tscore: null,
          score: ''
        }
      ],
      sel73: [
        {
          index: 1,
          name: '化学',
          score: ''
        },
        {
          index: 2,
          name: '历史',
          score: ''
        },
        {
          index: 3,
          name: '地理',
          score: ''
        },
        {
          index: 4,
          name: '政治',
          score: ''
        },
        {
          index: 5,
          name: '技术',
          score: ''
        },
        {
          index: 6,
          name: '物理',
          score: ''
        },
        {
          index: 7,
          name: '生物',
          score: ''
        }
      ],
      plusScoreArr: [['0分', '3分', '5分', '20分']],
      plusScoreVal: ['0分'],
      userInfo: [
        {
          name: '姓名',
          val: ''
        },
        {
          name: '手机号',
          val: ''
        },
        {
          name: '验证码',
          val: ''
        }
      ],
      examTypes: [
        { name: '1', txt: '普通考生', checked: false },
        { name: '2', txt: '艺体考生', checked: false }
      ],
      items: [
        { name: '1', value: '男', checked: 'true' },
        { name: '0', value: '女' }
      ],
      // array: ['美术类', '音乐类', '舞蹈类', '影视类', '时装类', '播音类', '编导类', '摄制类', '体育类'],
      artArr: [['美术类', '音乐类', '舞蹈类', '影视类', '时装类', '播音类', '编导类', '摄制类', '体育类']],
      artVal: ['美术类'],
      // 验证码相关
      smsCode: {
        text: '获取验证码',
        status: 0,
        interVal: null
      },
      // 成绩与位次相关
      scoreRank: {
        scores: ['', '', '', '', '', '', '', '', '', ''],
        plusScore: 0
      },
      examType: 1,
      // 艺考相关
      art: {
        examType: 1,
        artSubject: '美术类',
        artScore: ''
      },
      scoreCount: 0,
      selectSubject: [0, 0, 0, 0, 0, 0, 0],
      inputDisable: [false, false, false, false, false, false, false],
      scoreNow: '- / -',
      scoreLast: '- / -',
      plusScore: 0,
      score: '',
      rank: '',
      score2018: '',
      score2017: '',
      // 修改成绩次数
      changeCount: 0,
      // 修改选课次数
      subjectCount: 0
    }
  },
  created () {
    // 显示loading
    this.$vux.loading.show({
      text: '加载中...'
    })
    this.initData()
  },
  watch: {
    changeCount () {
      //  体验用户只有一次选课修改，2次成绩修改
      if (this.changeCount < 1 && this.userData.type === 102) {
        this.disabledStatus = true
      }
    }
  },
  methods: {
    // 获取是否可以修改名次和位次
    getChangeCount () {
      Api.getChangeCount().then(res => {
        if (res.code === 20000) {
          this.changeCount = res.data.value / 1
        }
      })
    },
    // 初始化数据
    initData () {
      let that = this
      // 从后台取最新的数据
      Api.getUserInfo().then(res => {
        Utils.local('userData', res.data)
        that.userData = res.data
        if (that.userData.examType === 2) {
          that.artVal = [that.userData.artSubject]
          that.art.examType = 2
          that.art.artSubject = that.userData.artSubject
          that.art.artScore = that.userData.artScore
          let _examItem = that.examTypes[1]
          _examItem.checked = true
          that.$set(that.examTypes, 1, _examItem)
        } else {
          let _examItem = that.examTypes[0]
          _examItem.checked = true
          that.$set(that.examTypes, 0, _examItem)
        }
        that.art.artSubject = that.userData.artSubject
          that.art.artScore = that.userData.artScore
        // 组建各科数据
        let sArr = ['语文', '数学', '外语', '化学', '历史', '地理', '政治', '技术', '物理', '生物']
        if (that.userData.scores) {
          that.mainSub = []
          that.sel73 = []
          let _scores = that.userData.scores.split(',')
          that.scoreRank.scores = []
          _scores.map((item, idx) => {
            let subItem = {
              index: idx,
              name: sArr[idx],
              score: parseFloat(item) > 0 ? parseFloat(item) : ''
            }
            that.scoreRank.scores.push(parseFloat(item) > 0 ? parseFloat(item) : '')
            if (idx < 3) {
              that.mainSub.push(subItem)
            } else {
              that.sel73.push(subItem)
              that.$set(that.inputDisable, idx - 3, subItem.score ? 0 : 1)
              that.$set(that.selectSubject, idx - 3, subItem.score ? 1 : 0)
            }
          })
        }
        that.score = that.userData.score ? that.userData.score : '-'
        that.rank = that.userData.rank ? that.userData.rank : '-'
        that.plusScore = that.userData.plusScore
        that.scoreCount = that.userData.examType === 2 ? parseInt(that.userData.artFinalScore) : that.userData.score
        if (that.userData.score2017) {
          that.score2017 = that.userData.score2017 ? that.userData.score2017 : '-'
          that.score2018 = that.userData.score2018 ? that.userData.score2018 : '-'
        } else {
          that.getAdviceScore()
        }

        // 获取是否可以修改选课和成绩
        if (that.userData.type === 102) {
          that.changeCount = that.userData.changeCount
          that.subjectCount = that.userData.subjectChangeCount
        } else {
          that.changeCount = 999
          that.subjectCount = 999
        }
        // 隐藏loading
        that.$vux.loading.hide()
      })
    },
    // 计算总分
    calcScoreCount () {
      let score = 0
      let _scoreRank = this.scoreRank
      let scores = _scoreRank.scores
      let _art = this.art

      for (let i = 0; i < scores.length; i++) {
        if (scores[i]) {
          score += scores[i] ? parseInt(scores[i]) : 0
        }
      }
      if (_art.examType == 2) {
        switch (_art.artSubject) {
          case '体育类':
          case '美术类':
          case '音乐类':
            score = score * 0.5 + _art.artScore * 7.5 * 0.5
            break
          case '舞蹈类':
          case '影视类':
          case '时装类':
            score = score * 0.4 + _art.artScore * 7.5 * 0.6
            break
          case '播音类':
            score = score * 0.8 + _art.artScore * 7.5 * 0.2
            break
          case '编导类':
          case '摄制类':
          default:
            score = score * 1
            break
        }
      }
      // this.scoreCount = score
      score += this.plusScore ? parseInt(this.plusScore) : 0
      this.score = parseInt(score)
      // 自动计算位次号
      this.getAdviceRank(this.score)
    },
    // 估算位次号
    getAdviceRank (score) {
      let qData = {
        type: this.art.examType === 2 ? this.art.artSubject : '普通类',
        score: score
      }
      if (score === 0) {
        this.scoreRank.rank = 0
      } else {
        Api.getRankAdvice(qData).then(res => {
          this.scoreRank.rank = res.message
          this.rank = res.message
          this.getAdviceScore()
        })
      }
    },
    // 估算2018/2017成绩
    getAdviceScore () {
      // 没有rank不获取2017/18的成绩
      if (!this.rank || this.rank === '-') return
      let qData = {
        type: this.art.examType === 2 ? this.art.artSubject : '普通类',
        rank: this.rank
      }
      Api.getScoreAdvice(qData).then(res => {
        let _score = res.message.split(',')
        this.score2017 = _score[0] === 'null' ? '-' : _score[0]
        this.score2018 = _score[1] === 'null' ? '-' : _score[1]
      })
    },
    // 验证分数是否超出，3门主科，还有7选3
    verifScore (score, max, idx) {
      let _item = this.mainSub[idx]
      if (isNaN(parseInt(score)) || !score) {
        score = 0
      } else if ((score * 1) > max / 1) {
        score = max
      }

      _item.score = score
      this.$set(this.mainSub, idx, _item)
      this.$set(this.scoreRank.scores, idx, score)

      // 计算总分
      this.calcScoreCount()
    },
    // 验证艺术分数是否超出
    verifArtScore (score) {
      let max = 100;
      if(score.length>3){
        score=max;
      }
      if ((score * 1) > max) {
        score = max
      }
      this.art.artScore = score;
      // 计算总分
      this.calcScoreCount()
    },
    // 科类代码选择
    onArtChange (val) {
      this.art.artSubject = this.artVal[0]
      this.calcScoreCount()
    },
    // 考生类型选择
    examTypeChang (idx) {
      if (!this.changeCount) return
      let _exam = this.examTypes[idx]
      this.examTypes.map((item, i) => {
        let _item = item
        _item.checked = false
        this.$set(this.examTypes, i, _item)
      })
      _exam.checked = true
      this.$set(this.examTypes, idx, _exam)
      this.art.examType = idx + 1
       this.calcScoreCount()
    },
    // 验证selected
    subjectClick (idx) {
      if (!this.subjectCount) return
      if (!this.verifSubjectCount(idx)) {
        this.$set(this.selectSubject, idx, false)
        return false
      }
      let nowSelect = this.selectSubject[idx]
      // 设置checkbox
      this.$set(this.selectSubject, idx, !nowSelect)
      // 如果当前checkbox已经选中，是取消选择，那么清空成绩
      if (nowSelect) {
        this.inputDisable = [false, false, false, false, false, false, false]
        this.$set(this.scoreRank.scores, (idx + 3), '')
        let _item73 = this.sel73[idx]
        _item73.score = null
        this.$set(this.sel73, idx, _item73)
      } else {
        this.$set(this.scoreRank.scores, (idx + 3), 0)
        let _item73 = this.sel73[idx]
        _item73.score = 0
        this.$set(this.sel73, idx, _item73)
        this.$set(this.inputDisable, idx, false)
      }
    },
    // 是否disable
    hasDisable (idx) {
      if (this.inputDisable[idx]) {
        // 超过3个
        this.$vux.toast.show({
          text: '最多选择3门科目，如需更改，请先取消勾选其他科目',
          type: 'text',
          width: '80%'
        })
      } else if (this.verifSubjectCount(idx)) {
        // 未超过3个，判断是否为0，0则赋值为空
        if (this.sel73[idx].score === 0) {
          let _sel73Item = this.sel73[idx]
          _sel73Item.score = ''
          this.$set(this.sel73, idx, _sel73Item)
        }
      }
    },
    // 验证选科数量
    verifSubjectCount (idx) {
      // 获取已经勾选的选科数量
      let _count = 0
      for (let i = 0; i < this.selectSubject.length; i++) {
        if (this.selectSubject[i]) {
          _count++
        }
      }

      if (_count > 2) {
        if (this.selectSubject[idx]) {
          return true
        } else {
          // 超过3个
          this.$vux.toast.show({
            text: '最多选择3门科目，如需更改，请先取消勾选其他科目',
            type: 'text',
            width: '80%'
          })
          return false
        }
      } else {
        return true
      }
    },
    // 验证勾选框
    verifSubject (score, max, idx) {
      if (this.verifSubjectCount(idx)) {
        // 少于3个
        let _item = this.sel73[idx]
        if (isNaN(parseInt(score)) || !score) {
          score = 0
        } else if ((score * 1) > max / 1) {
          score = max
        }
        _item.score = score
        this.$set(this.sel73, idx, _item)
        this.$set(this.selectSubject, idx, 1)
        this.$set(this.scoreRank.scores, idx + 3, score)
        // 空值赋为0
        if (!this.sel73[idx].score) {
          let _sel73Item = this.sel73[idx]
          _sel73Item.score = 0
          this.$set(this.sel73, idx, _sel73Item)
        }
        // 计算总分
        this.calcScoreCount()
        // 判断有没有超过3门选课
        let _count = 0
        for (let i = 0; i < this.selectSubject.length; i++) {
          if (this.selectSubject[i]) {
            _count++
          }
        }
        // 已经3们选课，设置disable
        if (_count > 2) {
          for (let i = 0; i < this.selectSubject.length; i++) {
            if (!this.selectSubject[i]) {
              this.$set(this.inputDisable, i, true)
            }
          }
        } else {
          this.inputDisable = [false, false, false, false, false, false, false]
        }
      }
    },
    onPlusScoreChange () {
      console.log(this.plusScoreVal)
    },
    saveScoureRank () {
      let that = this
      let _formData = that.scoreRank
      // 没有修改次数不操作
      if (this.changeCount === 0) {
        return false
      }
      // 验证分数
      let _scores = _formData.scores
      let _scoresCount = 0
      for (let i = 0; i < _scores.length; i++) {
        if (_scores[i] > 0) {
          _scoresCount++
        } else {
          _formData.scores[i] = 0
        }
      }
      if (_scoresCount !== 6) {
        that.$vux.toast.show({
          text: '请正确填写您的科目与成绩',
          type: 'text',
          width: '80%'
        })
        return
      }
      _formData.scores = _formData.scores.join(',')
      _formData.examType = that.art.examType
      _formData.plusScore = parseInt(that.plusScoreVal[0])
      _formData.rank = that.rank;
      return;
      // 判断是否艺体
      if (that.art.examType === 2) {
        if (!that.art.artScore) {
          that.$vux.toast.show({
            text: '请正确填写您的专业分数',
            type: 'text',
            width: '80%'
          })
          return
        }
        // 艺体
        _formData.artSubject = that.art.artSubject
        _formData.artScore = that.art.artScore
        Api.saveArtScoreRank(_formData).then(res => {
          if (res.code === 20000) {
            that.saveScoureSucc(res.data)
          }
        })
      } else {
        Api.saveScoreRank(_formData).then(res => {
          if (res.code === 20000) {
            that.saveScoureSucc(res.data)
          }
        })
      }
    },
    saveScoureSucc (userData) {
      let that = this
      Utils.local('userData', userData)
      that.$vux.toast.show({
        text: '保存成绩信息成功',
        type: 'text',
        width: '80%'
      })
      // 修改次数减少到0
      if (userData.type === 102) {
        this.changeCount = userData.changeCount
        this.subjectCount = userData.subjectChangeCount
        if (this.changeCount > 0 && this.subjectCount > 0) {
          this.updateSubjectAndChangeCount(0)
        } else if (this.changeCount > 0) {
          this.updateSubjectAndChangeCount(1)
        }
      }
      if (that.$route.query.redirect) {
        that.$router.push({name: that.$route.query.redirect})
      } else {
        that.$router.push({name: 'mineIndex'})
      }
    },
    // 修改成绩修改剩余次数
    updateChangeCount () {
      Api.updateChangeCount().then(res => {
        if (res.code === 20000) {
          this.changeCount--
        }
      })
    },
    // 修改选课剩余次数
    updateSubjectCount () {
      Api.updateSubjectCount().then(res => {
        if (res.code === 20000) {
          this.subjectCount--
        }
      })
    },
    // 修改选课次数&成绩次数
    updateSubjectAndChangeCount (typeVal) {
      // 0 同时修改  1 changeCount  2 subjectCount
      Api.updateSubjectAndChangeCount({ type: typeVal }).then(res => {
        if (res.code === 20000) {
          this.subjectCount--
          this.changeCount--
        }
      })
    },
    // 主课程点击输入方法
    onMainClick (idx) {
      // 判断是否为0，0则赋值为空
      if (this.mainSub[idx].score === 0) {
        let _mainItem = this.mainSub[idx]
        _mainItem.score = ''
        this.$set(this.mainSub, idx, _mainItem)
      }
    },
    // 去购买
    gotoBuy () {
      this.$router.push({name: 'goodsPay', query: {t: 'all'}})
    }
  }
}
</script>

<style lang="scss">
.reg-group{
  .weui-cells{
    margin-top: 0 !important;
  }
  .vux-popup-picker-select{
    padding-left: .64rem;
    text-align: left !important;
    .vux-popup-picker-value{
      color: #FF8600;
      position: relative;
      padding-right: .4rem;
    }
  }
  .points-pop{
    .vux-popup-picker-select{
      padding-left: 1rem;
    }
  }
.def-ipt{
  .weui-input{
    color: #FF8600;
    -webkit-text-fill-color: initial !important;
  }
}
  .vux-popup-picker-placeholder{
    color: #777;
  }
}
.bonus-wrap{
  .weui-cell__bd{
    p{
      margin: 0;
    }
  }
  .weui-cell__ft{
    width: 24px;
    height: 24px;
    border-radius: 4px;
    border: 1px solid #ccc;
    padding-left: 0 !important;
    .weui-icon-checked::before{
      color: #FF8600 !important;
    }
  }
}
.highlight .weui-input{
  color: #FF8600 !important;
  -webkit-text-fill-color: #FF8600 !important;
  -o-text-fill-color: #FF8600 !important;
}
</style>

<style lang="scss" scoped>
.btn-next-group{
  padding-bottom: 1.6rem;
}
.reg-page{
  background-color: #F5F5F5;
  min-height: 100%;
  .reg-title{
    font-size: 16px;
    color: #999;
    padding: .16rem .4rem;
  }
  .reg-tip{
    padding: .266667rem .4rem;
    font-size: 13px;
    // text-align: justify;
    color: #f00;
    .goto-buy-wrap{
      display: inline-block;
      margin-left: .213333rem /* 8/37.5 */;
      position: relative;
      .goto-buy-img{
        position: absolute;
        left: 0;
        top: 0;
        width: 26px;
      }
      .goto-buy{
        color: #fff;
        background: #FF8600;
        padding: 4px 8px;
        border-radius: 4px;
      }
    }
  }
  .sel-item {
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    font-size: 14px;
    padding: 10px 15px !important;
    position: relative;
    &::before{
      content: " ";
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      height: 1px;
      border-top: 1px solid #D9D9D9;
      color: #D9D9D9;
      -webkit-transform-origin: 0 0;
      transform-origin: 0 0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      left: 15px;
    }
    &:last-child{
      border-bottom: none;
    }
    .label {
      width: 80px;
    }
    .ipt-item{
      -webkit-box-flex: 1;
      -webkit-flex: 1;
      flex: 1;
      input {
        width: 100%;
        border: 0;
        outline: 0;
        -webkit-appearance: none;
        background-color: transparent;
        font-size: inherit;
        color: inherit;
        height: 1.41176471em;
        line-height: 1.41176471;
        color: #FF8600;
      }
    }
    .check-room{
      width: 24px;
      height: 24px;
      border-radius: 4px;
      border: 1px solid #ccc;
      padding-left: 0 !important;
      .i-checked::before{
        content: '\EA08';
        display: block;
        color: #FF8600;
        font-size: 16px;
        margin-left: .2em;
        margin-right: .2em;
      }
    }
  }
  .radio-group{
    .radio-item{
      margin-right: .4rem;
      &::last-child{
        margin-right: 0;
      }
      .radio-room{
        display: inline-block;
        width: 22px;
        height: 22px;
        border: 1px solid #ccc;
        border-radius: 50%;
        .i-checked::before{
          content: '\EA08';
          display: block;
          color: #FF8600;
          font-size: 16px;
          margin-left: .15em;
          margin-right: .15em;
        }
      }
      .radio-txt{
        display: inline-block;
        margin-left: .16rem;
        line-height: 22px;
      }
    }
  }
}
</style>
